package com.example.bindservice;
import androidx.appcompat.app.AppCompatActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private MyService.MyBinder myBinder;
    private MyConn myConn;
    private Button btn_bind,btn_call,btn_unbind;
    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
    }

    private void init() {
        btn_bind=(Button) findViewById(R.id.btn_bind);
        btn_call=(Button) findViewById(R.id.btn_call);
        btn_unbind=(Button) findViewById(R.id.btn_unbind);
        btn_bind.setOnClickListener(this);
        btn_call.setOnClickListener(this);
        btn_unbind.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch(view.getId()){
            case R.id.btn_bind:
                if(myConn==null){
                    myConn=new MyConn();  //创建连接服务对象
                }
                Intent intent=new Intent(MainActivity.this,MyService.class);
                bindService(intent,myConn,BIND_AUTO_CREATE);  //绑定服务对象
                break;
            case R.id.btn_call:
                myBinder.callMethodInService();          //调用服务中的方法
                break;
            case R.id.btn_unbind:
                if(myConn!=null){
                    unbindService(myConn);
                    myConn=null;
                }
                break;
        }
    }
    //创建MyConn类，用于实现连接服务
    private class MyConn implements ServiceConnection {
        //当成功绑定服务时调用的方法，该方法获取MyService中的Ibinderduix
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            myBinder=(MyService.MyBinder)iBinder;
            Log.i(TAG, "服务成功绑定，内存地址为："+myBinder.toString());
        }
        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    }
}
